/**
 * 
 */
package com.epam.traning.taskmanager.service;

import java.util.List;

import org.json.JSONObject;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.os.IBinder;

import com.epam.traning.taskmanager.content.contract.TaskContract;
import com.epam.traning.taskmanager.http.HttpRequestBuilder;
import com.epam.traning.taskmanager.http.HttpRequestBuilder.Type;
import com.epam.traning.taskmanager.task.common.ListJsonObjectTask;
import com.epam.traning.taskmanager.task.common.ParamCallback;

/**
 * @author IstiN
 *
 */
public class HttpService extends Service implements ParamCallback<List<JSONObject>> {

	public static final String EXTRA_KEY_MESSAGE = "message";

	public static final String ACTION_ON_ERROR = "com.epam.traning.taskmanager.service.ACTION_ON_ERROR";
	
	public static final String ACTION_ON_SUCCESS = "com.epam.traning.taskmanager.service.ACTION_ON_SUCCESS";
	
	public static final String HTTP_REQUEST_BUILDER = "http_request_builder";

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
	    handleCommand(intent);
	    // We want this service to continue running until it is explicitly
	    // stopped, so return sticky.
	    return START_STICKY;
	}

	protected void handleCommand(Intent intent) {
		if (intent == null) {
			return;
		}
		HttpRequestBuilder httpRequestBuilder = (HttpRequestBuilder) intent.getSerializableExtra(HTTP_REQUEST_BUILDER);
		if (httpRequestBuilder == null) {
			return;
		}
		if (httpRequestBuilder.getType() == Type.GET) {
			new ListJsonObjectTask(this).start(httpRequestBuilder.getUrl());
		}
		//RestProcessor.get(this).asyncProcess(this, config);
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onSuccess(final List<JSONObject> p) {
		Intent intent = new Intent(ACTION_ON_SUCCESS);
		sendBroadcast(intent);
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for (JSONObject jsonObject : p) {
					ContentValues contentValues = new ContentValues();
					contentValues.put("data", jsonObject.toString());
					getContentResolver().insert(TaskContract.TasksColumns.CONTENT_URI, contentValues);
				}				
			}
			
		}).start();
	}

	@Override
	public void onError(Throwable e) {
		Intent intent = new Intent(ACTION_ON_ERROR);
		intent.putExtra(EXTRA_KEY_MESSAGE, e.getMessage());
		sendBroadcast(intent);
	}

}
